package com.example.pungolo.journal.view;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Stack;

import com.example.pungolo.journal.R;
import com.example.pungolo.journal.model.DateUtils;
import com.example.pungolo.journal.model.DiaryPage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class DiaryPageView extends LinearLayout {
  TextView dayLabelView;
  ImageView photoView;
  ScrollView scrollView;
  LinearLayout diaryEntryContainer;
  DiaryPage page;
  View content;
  private final static DateFormat dateFormat = SimpleDateFormat.getDateInstance();
  private Stack<DiaryEntryView> entryGarbage = new Stack<DiaryEntryView>();
  private OnClickListener onEntryClickedListener;
  private OnLongClickListener onEntryLongClickedListener;
  private OnClickListener onMyEntryClickedListener;
  private OnLongClickListener onMyEntryLongClickedListener;
  private OnClickListener onAddEntryClickedListener;
  private OnClickListener onPhotoViewClicked;
  private Bitmap currentBitmap;

  public DiaryPageView(Context context) {
    super(context);
    init();
  }

  public DiaryPageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  @SuppressLint("NewApi")
  public DiaryPageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
  }

  private void init() {
    Context context = getContext();

    // Gonfia la view dall'xml!
    View.inflate(context, R.layout.diary_page_view, this);

    this.content = this.getChildAt(0);
    this.dayLabelView = (TextView) findViewById(R.id.day_label);
    this.photoView = (ImageView) findViewById(R.id.photo);
    this.diaryEntryContainer = (LinearLayout) findViewById(R.id.entry_container);
    
    this.photoView.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        photoViewClicked();
      }
    });

    DiaryEntryView[] buttons;
    buttons = new DiaryEntryView[20];
    this.onMyEntryClickedListener = new OnClickListener() { public void onClick(View v) { entryClicked((DiaryEntryView) v); } };
    //this.onMyEntryLongClickedListener = new OnLongClickListener() { public boolean onLongClick(View v) { return entryLongClicked((DiaryEntryView) v); } };
    for (int i = 0; i < buttons.length; i++) {
      buttons[i] = newDiaryEntryView();
      // buttons[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
      // LayoutParams.WRAP_CONTENT));
      diaryEntryContainer.addView(buttons[i]);
    }

    // Finch� non viene impostata una DiaryPage, lascio questa view
    // complemente vuota
    removeAllViews();
  }

  public void setDiaryPage(DiaryPage page) {
    if (page != null) {
      // Riaggiungo il contenuto se prima non c'era una DiaryPage
      if (this.page == null)
        this.addView(this.content);
      dayLabelView.setText(dateFormat.format(page.getDate()));
      recycleAllDiaryEntryViews();
      int c = page.getEntryCount();
      for (int i = 0; i < c; i++) {
        DiaryEntryView b = newDiaryEntryView();
        b.setEntry(page.getEntry(i));
        diaryEntryContainer.addView(b);
      }
      if (DateUtils.dayFromDate(page.getDate()) == DateUtils.dayFromDate(new Date())) {
        Button addEntryButton = new Button(this.getContext());
        addEntryButton.setText(R.string.add_entry);
        addEntryButton.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
            addEntryClicked();
          }
        });
        diaryEntryContainer.addView(addEntryButton);
      }

      String path = page.getImagePath();
      if (path == null) {
        // La foto non esiste, metto quella di default
        photoView.setImageResource(R.drawable.default_photo);
      } else if (new File(path).exists()) {
        // Carica l'immagine nella photoView
        this.photoView.setImageResource(R.drawable.default_photo);
        
        Context ctx = getContext();
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        display.getMetrics(displaymetrics);
        Point size = new Point(displaymetrics.widthPixels, displaymetrics.heightPixels);
        
        BitmapWorkerTask task = new BitmapWorkerTask(this, size, null);
        task.execute(path);
      } else {
        // Il file dell'immagine non esiste, mi sa che è stata cancellata
        photoView.setImageResource(R.drawable.default_photo);
      }
    } else {
      removeAllViews();
      recycleAllDiaryEntryViews();
    }
    this.page = page;
  }

  public DiaryPage getDiaryPage() {
    return page;
  }

  private DiaryEntryView newDiaryEntryView() {
    if (entryGarbage.size() > 0)
      return entryGarbage.pop();
    DiaryEntryView v = new DiaryEntryView(getContext());
    v.setOnClickListener(this.onMyEntryClickedListener);
    v.setOnLongClickListener(this.onMyEntryLongClickedListener);
    return v;
  }

  private void recycleAllDiaryEntryViews() {
    int c = diaryEntryContainer.getChildCount();
    for (int i = 0; i < c; i++) {
      View c1 = diaryEntryContainer.getChildAt(i);
      if (c1 instanceof DiaryEntryView)
        entryGarbage.push((DiaryEntryView) c1);
    }
    diaryEntryContainer.removeAllViews();
  }

  public void setOnEntryClickedListener(OnClickListener onClickListener) {
    this.onEntryClickedListener = onClickListener;
  }
  public void entryClicked(DiaryEntryView v) {
    if (this.onEntryClickedListener != null)
      onEntryClickedListener.onClick(v);
  }
  
  public void setOnEntryLongClickedListener(OnLongClickListener onLongClickListener) {
    this.onEntryLongClickedListener = onLongClickListener;
  }
  protected boolean entryLongClicked(DiaryEntryView v) {
    if (this.onEntryLongClickedListener != null)
      return onEntryLongClickedListener.onLongClick(v);
    return false;
  }
  
  public void setOnAddEntryClickedListener(OnClickListener onClickListener) {
    this.onAddEntryClickedListener = onClickListener;
  }
  public void addEntryClicked() {
    if (this.onAddEntryClickedListener != null)
      onAddEntryClickedListener.onClick(this);
  }
  
  public void setOnPhotoViewClicked(OnClickListener onClickListener) {
    this.onPhotoViewClicked = onClickListener;
  }
  protected void photoViewClicked() {
    if (this.onPhotoViewClicked != null)
      onPhotoViewClicked.onClick(this);
  }

  public void setImageBitmap(Bitmap bm) {
    if (this.currentBitmap != null)
      this.currentBitmap.recycle();
    this.currentBitmap = bm;
    this.photoView.setImageBitmap(bm);
  }
}
